/*!
    \copyright  Copyright (c) 2025 Qualcomm Technologies International, Ltd.
                All Rights Reserved.
                Qualcomm Technologies International, Ltd. Confidential and Proprietary.
    \file
    @{
        \ingroup    adkfs
        \brief      Utilities to work with AdKFs files
*/
#include <adkfs.h>

#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>

int32_t AdkFs_Cp(const char* src_filepath, const char* dst_filepath)
{
    if (0 == strcmp(src_filepath, dst_filepath))
    {
        return EINVAL;
    }

    adkfs_fhandle_t src_handle;
    adkfs_fhandle_t dst_handle;
    int32_t rc = 0;

    rc = AdkFs_Fopen(&src_handle, src_filepath, ADKFS_FOPEN_READ);
    if (!ADKFS_SUCCESS(rc))
    {
        return rc;
    }

    rc = AdkFs_Fopen(&dst_handle, dst_filepath, ADKFS_FOPEN_WRITE);
    if (!ADKFS_SUCCESS(rc))
    {
        return rc;
    }

    size_t fsize = 0;
    rc = AdkFs_Fsize(src_filepath, &fsize);
    if (!ADKFS_SUCCESS(rc))
    {
        return rc;
    }

    uint8_t* src_buffer = NULL;
    bool is_buffer_in_heap = FALSE;
    rc = AdkFs_Fmap(src_handle, &src_buffer);

    if (EOPNOTSUPP == rc)
    {
        src_buffer = malloc(fsize);
        is_buffer_in_heap = TRUE;
        size_t bytes_read = 0;
        rc = AdkFs_Fread(src_handle, src_buffer, fsize, &bytes_read);
    }
    else if (!ADKFS_SUCCESS(rc))
    {
        return rc;
    }
    size_t bytes_written = 0;
    rc = AdkFs_Fwrite(dst_handle, src_buffer, fsize, &bytes_written);
    if (!ADKFS_SUCCESS(rc))
    {
        return rc;
    }

    if (is_buffer_in_heap)
    {
        free(src_buffer);
    }

    rc = AdkFs_Fclose(&src_handle);
    if (!ADKFS_SUCCESS(rc))
    {
        return rc;
    }

    rc = AdkFs_Fclose(&dst_handle);
    if (!ADKFS_SUCCESS(rc))
    {
        return rc;
    }

    return 0;
}

/*! @} */
